﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using SharePointListSecurity.Model;


namespace SharePointListSecurity.WebControls
{
    class CustomAlertNotifier : IAlertNotifyHandler
    {

        /// <summary>
        /// this method send mail notification 
        /// to users  
        /// </summary>
        public bool OnNotification(SPAlertHandlerParams ahp)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {              
                var site = new SPSite(ahp.siteUrl + ahp.webUrl);
                var sPWeb = site.OpenWeb();
                var list = sPWeb.Lists[ahp.a.ListID];
                var currentUser = sPWeb.AllUsers.GetByID(ahp.a.UserId);
                var sharepointListSecurityService = new SharepointListSecurityService(sPWeb, currentUser);
                var hiddenFields = sharepointListSecurityService.GetHiddenFields(list, SPControlMode.Display)
                                                                .Select(x => x.Title).ToList();

                ahp.body = GetEmailBody(ahp.body, hiddenFields);
                SPUtility.SendEmail(sPWeb, ahp.headers, ahp.body);
            });
            return false;
        }
        /// <summary>
        /// this method hide fields from the mail body 
        /// by deleting them from html
        /// </summary>
        private string GetEmailBody(string body, List<string> hiddenFields)
        {
            int beginOfBody = body.IndexOf("<body>");
            int endOfBody = body.IndexOf("</body>");
            string header = body.Substring(0, beginOfBody);
            string footer = body.Substring(endOfBody + 7);
            string corp = body.Substring(beginOfBody, body.Length - header.Length - footer.Length);  
            string[] elements = corp.Split(new string[] { "<tr>" }, StringSplitOptions.None);
       
            foreach (var current in elements)
            {
                foreach (var hiddenField in hiddenFields)
                {
                    if (Regex.Match(current, "<td.*?>" + hiddenField + ":</td>").Success)
                    {
                        corp = corp.Replace("<tr>" + current, "");
                    }
                }
            }

            return header + corp + footer;
        }

    }
}
